package com.manning.readinglist.config;

import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import javax.sql.DataSource;

public class DataSourceHikariBuilder {

    private static ResourceLoader loader = new DefaultResourceLoader();
    private static String MYBATIS_SETTING = "classpath:/mybatis-config.xml";

    public static DataSource buildDataSource(DatasourceProperties properties) {
        HikariDataSource hikari = new HikariDataSource();
        hikari.setJdbcUrl(properties.getUrl());
        hikari.setUsername(properties.getUsername());
        hikari.setPassword(properties.getPassword());
        hikari.setDriverClassName("com.mysql.cj.jdbc.Driver");
        hikari.setPoolName("HikariCP_Pool");
        hikari.setMaximumPoolSize(properties.getMaxActive());
        hikari.setMinimumIdle(properties.getMinIdle());
        hikari.setIdleTimeout(100000);
        hikari.setMaxLifetime(300000);
        hikari.setConnectionTimeout(15000);
//        hikari.setConnectionTestQuery("SELECT 1");
//        hikari.setValidationTimeout(3000);
//        hikari.setAutoCommit(true);
        hikari.setInitializationFailTimeout(5000);
        return hikari;
    }

    public static SqlSessionFactoryBean buildSqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setConfigLocation(loader.getResource(MYBATIS_SETTING));
        return factory;
    }
}
